<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/18
 * Time: 13:59
 */

class package extends MY_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model('product_model');
        $this->load->model('package_model');
    }

    /**
     * 首页
     */
    public function index(){
        $this->GetPackageData();
    }
    /**
     * 添加包裹
     * @param $orderId
     */
    function AddPackage($orderId=''){
        $gp=gp();
        if($gp && $orderId) {
            $gp['order_id']=$orderId;
            if($gp['weight']==''){
                $gp['weight']=0;
            }
            $array_id=implode(',',$gp['product_id']);
            //存入产品编号
            $gp['product_id']=$array_id;
            //添加包裹数据
            $addPackageBool = $this->package_model->AddPackageData($gp);
            if($addPackageBool){
                //修改产品状态改为已发货
                $this->product_model->UpdateProductStatus($array_id,$orderId);
            }
            $this->GetPackageData();
        }
    }

    /**
     * 获取包裹数据
     */
    public function GetPackageData(){
        $gp=gp();
        //条件判断
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?keyword='.$gp['keyword'].'&type='.$gp['type'].'&country='.$gp['country'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('orders/package/GetPackageData'.$str);
        $config['total_rows'] = $this->package_model->CountPackageNum(trim($gp['keyword']),$gp['type'],$gp['country']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();
        //包裹数据
        $packageList=$this->package_model->GetPackageData($this->users['franchisees_id'],trim($gp['keyword']),$gp['type'],$gp['country'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        $data['packageList']=$packageList;
        $data['keyword']=$gp['keyword'];
        $data['type']=$gp['type'];
        $data['country']=$gp['country'];
        //发货国家数据
        $data['countryList']=$this->package_model->getCountry();
        $this->load->view('defaults/Package_list',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 提交包裹数据至Nacex
     */
    public function PostNacex(){
        $gp=gp();
        $this->load->library('nacex/classes/Nacex');
        $naCex=new Nacex();
        $bachOrder=$this->package_model->GetBatchPackage($gp['pkId']);
        foreach($bachOrder as $row){
            $data=array(
                'name'=>$row['consignee'],
                'zipcode'=>$row['zipcode'],
                'city'=>$row['city'],
                'phone'=>$row['phone'],
                'country'=>$row['country'],
                'orderID'=>$row['package_id'],
                'address'=>$row['RECEIPT'],
            );
            $data=$naCex->putExpedicion($data);
            if($data['code']==1 && $data['msg']) {
                $agencia=explode('/',$data['msg']);
                $etiqueta=$naCex->getEtiqueta($agencia[0],$agencia[1]);
                $documents=$naCex->saveEtiqueta($etiqueta['result'],$row['package_id'].'.png');
                $uDate = array(
                    'documents'=>$documents,
                    'trace_id' => $data['msg'],
                    'is_package' => 1,
                );
               // $this->package_model->UpdateProductShipoutTrack($bachOrder['order_id'],$agencia[1]);
                $this->common_model->update('mt_order',array('shipoutTrack'=>$data['msg']),array('order_num'=>$row['order_id']));
                $product_id=explode(',',$row['product_id']);
                foreach($product_id as $key=>$val) {
                    $this->common_model->resetStatus($val);
                }

            }else{
                $uDate = array(
                    'trace_id' => 'error Address information is incomplete',
                    'is_package' => 2,
                );
            }
            $this->package_model->UpdatePackageData($row['id'],$uDate);
        }
        redirect(blang_url('orders/package?keyword='.$gp['keyword']));
    }
    /**
     * 发送包裹信息至DHL
     */
    public function sendDHL(){
        $gp=gp();
        $this->load->library('DHL');
        $dhl = new DHL();
        $bachOrder=$this->package_model->GetBatchPackage($gp['pkId']);
        foreach($bachOrder as $row) {
            //receiver details
            $order_info=$this->package_model->GetOrderInfo($row['oid']);
            $street_number=explode(' ',$order_info['delivery_street_address']);
            $customer_details = array(
                'first_name'    => $order_info['consumer_name'],
                'last_name'     => $order_info['consumer_name'],
                'c/o'           => '',
                'street_name'   => $order_info['delivery_street_address'],
                'street_number' => $street_number[1]?$street_number[1]:'0',
                'country'       => $order_info['delivery_country'],
                'countryISOCode'   => $order_info['delivery_country'],
                'zip'           => $order_info['delivery_zipcode'],
                'city'          => $order_info['delivery_city'],
                'addressAddition' => '',
                'email'           => $order_info['consumer_email'],
                'phone'           => $order_info['consumer_phone'],
                'contact_person'  => $order_info['consumer_name'],
                'customerReference'  => $row['package_id']
            );
            //$response = $dhl->getVersion();
            $response = $dhl->createNationalShipment($customer_details);
            if($response !== false){
                if($response['statusCode']==='0') {
                    $uDate = array(
                        'documents' => $response['label_url'],
                        'trace_id' => $response['shipment_number'],
                        'is_package' => 1,
                    );
                    //更新订单追踪号
                    $this->common_model->update('mt_order',array('shipoutTrack'=>$response['shipment_number']),array('order_num'=>$row['order_id']));
                    $product_id=explode(',',$row['product_id']);
                    foreach($product_id as $key=>$val) {
                        $this->common_model->resetStatus($val);
                    }
                }else{
                    $uDate = array(
                        'trace_id' => 'error Address information is incomplete',
                        'is_package' => 2,
                    );
                }
                //更新包裹
                $this->package_model->UpdatePackageData($row['id'],$uDate);
            }else{
                var_dump($dhl->errors);
            }
        }
        redirect(blang_url('orders/package?keyword='.$gp['keyword']));
    }
}